﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Borg.Framework
{
    public class CreateCommand : ICommand
    {
        private readonly string[][] _arguments =
            new[]
                {
                    new[] { "shared", "unique" },
                    new[] { "ExtensionTypeInfo" }
                };

        private string Create(string[] command)
        {
            string item;

            if (command.Length < 2)
                return "Too few arguments.";

            if (!RuntimeCommands.ContainsArgument(command[1], _arguments[0]))
                return string.Format(
                    "Invalid argument \"{0}\". \"shared\" or \"unique\" expected.", command[1]);

            if (command.Length < 3)
                return "Too few arguments.";

            if (!RuntimeCommands.ContainsArgument(command[2], _arguments[1]))
                return string.Format(
                    "Invalid argument \"{0}\". \"ExtensionTypeInfo\" expected.", command[1]);

            if (command.Length < 4)
                return "  Too few arguments.";

            var elements = RuntimeCommands.Find(command, 2, out item);

            if (elements.Length == 0)
                return item;

            var builder = new StringBuilder();
            
            foreach (ExtensionTypeInfo eti in elements)
            {
                var ei = command[1].Equals("shared", StringComparison.CurrentCultureIgnoreCase)
                    ? eti.CreateSharedExtension()
                    : eti.CreateUniqueExtension();

                if (ei != null)
                    builder.AppendFormat("Extension {0}:\"{1}\" created.", ei.Id, ei.Name);
                else
                    builder.AppendFormat("Error on creating Extension \"{0}\"", eti.Name);
            }

            return builder.ToString();
        }

        public IEnumerable<string> GetArguments(string[] command, int pos)
        {
            if (pos == 0)
                return _arguments[0];

            if (pos == 1)
                return _arguments[1];

            if (pos != 2 || command.Length < 3 || command[2] != "ExtensionTypeInfo")
                return null;

            var args = new string[Runtime.Repository.ExtensionTypeInfos.Count];

            for (var i = 0; i < args.Length; i++)
                args[i] = Runtime.Repository.ExtensionTypeInfos[i].Name;

            return args;
        }

        public CommandHandler Handler
        {
            get { return Create; }
        }

        public string Help
        {
            get { return "  Help for command \"create\""; }
        }

        public string Name
        {
            get { return "create"; }
        }
    }
}

